var functionMap = new Map();
var currentTreeNode;
var form,
    upload;

$(document).ready(function () {
    $("#edit_node").css("display", "none");
    addEvent(document.getElementById('addBaseFunBtn'), 'click', addBaseFun);
    addEvent(document.getElementById('addPeerFunBtn'), 'click', addPeerFun);
    addEvent(document.getElementById('addChildFunBtn'), 'click', addChildFun);
    addEvent(document.getElementById('removeFunBtn'), 'click', removeFun);
});

layui.use(['form','upload'],function () {
    form = layui.form;
    upload = layui.upload;

    initTree();

    form.on('submit(sub)', function (data) {
        saveData(data);
    })
});


/***
 * 加载树
 * */
function initTree() {
    // 先清空
    $('#functionTree').html('');

    $.ajax({
        async: false,
        type: 'post',
        dataType: "json",
        url: '/sys-function/list',
        data: {},
        contentType:'application/x-www-form-urlencoded; charset=UTF-8',
        timeout: 30000,//超时时间设置为1分钟；
        success: function (data) {
            if (data.code == 0) {
                renderTree(formatData(data, "parentId", "id", "functionName"));
            } else {
                layer.alert(data.msg, {title: '错误信息：'});
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
        },
        error: function (a, b, c) {
            // 请求出错处理,依然初始化咨询节点信息
            if (b == 'timeout') {
                layer.alert("请求超时，请再次尝试！", {title: '错误信息：'});
            } else {
                layer.alert(url + "请求异常", {title: '错误信息：'});
            }
        }
    });

    //加载文件
    loadFile();
}

function renderTree(values){
    layui.use('tree', function(){
        layui.tree({
            elem: '#functionTree' //传入元素选择器
            ,nodes: values
            ,click: function(node){
                $(".funText").text("  --  "+ node.name);
                treeselected(node);
            }
        });
    });
}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatData(values, pid, id, name){
    var tree = [],
        item;

    var map = new Map();

    // 全局Map要清空
    functionMap.clear();

    // 1)变格式保存到Map
    for (var i = 0; i < values.List.length; i++) {
        functionMap.set(values.List[i][id], values.List[i]);

        item = new Object();

        item.name = values.List[i][name];
        item.value = JSON.stringify(values.List[i]).replace(/"/g, "'");
        item.children = [];

        map.set(values.List[i][id], item);
    }

    // 2)作为子项目加到父项目的list
    for (var i = 0; i < values.List.length; i++) {
        if (values.List[i][pid] > 0){
            var obj = map.get(values.List[i][pid]);
            obj.children.push(map.get(values.List[i][id]));
        } else {
            tree.push(map.get(values.List[i][id]));
        }
    }

    // 3)删除没有子项目的list
    for (var i = 0; i < values.List.length; i++) {
        var obj = map.get(values.List[i][id]);
        if (obj.children.length == 0) {
            delete obj.children;
        }
    }

    return tree;
}
/***
 * 选择树节点
 * */
function treeselected(e) {

    $("#edit_node").css("display", "block");
    var node = JSON.parse(e.value.replace(/'/g, '"'));
    currentTreeNode = node;
    $("#id").val(node.id);

    var parent = node.parentId ? functionMap.get(node.parentId) : null;

    form.val("formTest", {
        "parentName": parent ? parent.functionName : ''
        ,"functionName": node.functionName
        ,"functionUrl": node.functionUrl
        ,"functionState": node.functionState == 1 ? "1" : "3"
        ,"functionSort": node.functionSort
    });

    $("#parentName").html(parent ? parent.functionName : '');
    // 1）显示图片
    if (node.iconId > 0) {
        $('#iconId').val(node.iconId);
        $('#icon').attr('src', '/file/view/' + node.iconId);
    } else {
        $('#icon').attr('src', '/images/icon/timg.gif');
    }
}

//添加根节点
function addBaseFun() {
    var data = {
        'functionName': 'newNode',
        'functionSort': 0,
        'parentId': 0
    };
    ActHttpRequest("/sys-function/add", data, function (d) {
        if(d.code == 0){
            refershTree();
            layer.msg('添加成功！', {icon: 1});
        }
    })
}

//添加同级节点
function addPeerFun() {

    if(currentTreeNode != null && currentTreeNode.id != null){
        var data = {
            'functionName': 'newNode',
            'functionSort': '0',
            'parentId': currentTreeNode.parentId,
        };
        ActHttpRequest("/sys-function/add", data, function (d) {
            if(d.code == 0){
                refershTree();
                layer.msg('添加成功！', {icon: 1});
            }
        })
    }else{
        layer.open({
            title: '提示',
            icon: 0,
            content: '请选择节点！'
        })
    }
}

//添加子节点
function addChildFun() {
    if(currentTreeNode != null && currentTreeNode.id != null){
        var data = {
            'functionName': 'newNode',
            'functionState': '1',
            'functionSort': '0',
            'parentId': currentTreeNode.id,
        };
        ActHttpRequest("/sys-function/add", data, function (d) {
            if(d.code == 0){
                refershTree();
                layer.msg('添加成功！', {icon: 1});
            }
        })
    }else{
        layer.open({
            title: '提示',
            icon: 0,
            content: '请选择节点！'
        })
    }
}

//删除节点
function removeFun() {
    if(currentTreeNode != null && currentTreeNode.id != null){
        layer.confirm("您确定要删除【" + currentTreeNode.functionName + "】吗？",{
                btn: ['确定','取消'] //按钮
            },
            function () {
                // 1)取出所有子菜单
                currentTreeNode.functionState = 2;
                var ids = getChilds([currentTreeNode.id]);
                var values = [];
                var tmpFunction;
                if (ids.length > 0) {
                    for (var i = 0; i < ids.length; i++) {
                        tmpFunction = functionMap.get(ids[i]);
                        tmpFunction.functionState = currentTreeNode.functionState;
                        values.push(tmpFunction);
                    }
                }
                values.push(currentTreeNode);

                ActHttpRequest("/sys-function/update/", {functionList: JSON.stringify(values)}, function (data) {
                    if (data.code == 0) {
                        refershTree();
                        layer.msg('删除成功！', {icon: 1});
                    } else {
                        layer.alert(data.message, {icon: 5});
                    }
                }, null, null, null, '删除中。。。', true);
            },
            function () {
                
            });
    }else{
        layer.open({
            title: '提示',
            icon: 0,
            content: '请选择节点！'
        })
    }
}

/***
 * 保存数据
 * */
function saveData(data) {
    // 取得表单的所有字段值
    var formData = data.field;

    currentTreeNode.functionName = formData.functionName;
    currentTreeNode.functionUrl = formData.functionUrl;
    currentTreeNode.functionSort = formData.functionSort;
    currentTreeNode.functionState = formData.functionState;

    // 1)取出所有子菜单
    var ids = getChilds([currentTreeNode.id]);
    var values = [];
    var tmpFunction;
    if (ids.length > 0) {
        for (var i = 0; i < ids.length; i++) {
            tmpFunction = functionMap.get(ids[i]);
            tmpFunction.functionState = currentTreeNode.functionState;
            values.push(tmpFunction);
        }
    }
    values.push(currentTreeNode);

    ActHttpRequest("/sys-function/update", {functionList: JSON.stringify(values)}, function (data) {
        if (data.code == 0) {

            layer.msg('保存成功！', {icon: 1});
            refershTree();
        } else {
            layer.msg(data.message, {icon: 5});
        }
    }, null, null, null, '保存中。。。', true);
}

function refershTree() {
    initTree();
    $("#edit_node").css("display", "none");
    $("#fun").text("");
}

/**
 * 上传回调
 * @param fileId
 */
function loadFile() {
        //执行实例
        var uploadInst = upload.render({
            elem: '#upload' //绑定元素
            , url: '/file/upload' //上传接口
            , data: {}
            , async : false
            ,before: function(obj){
                obj.preview(function(index, result){
                    $('#icon').attr('src', result); //图片链接（base64）
                });
            }
            , done: function (data) {
                var url = '/file/view/'+data.id;

                currentTreeNode.iconId = data.id;
                $('#icon').attr('src', url);
            }

            , error: function () {
                //请求异常回调
            }
        });
}

/**
 * 取得授权功能子节点Id一览
 */
function getChilds(ids) {
    var result = [];

    for (value of functionMap) {
        if (ids.indexOf(value[1].parentId) >= 0) {
            result.push(value[1].id);
        }
    }

    if (result.length > 0){
        result = result.concat(getChilds(result));
    }

    return result;
}